package com.hlyj.http.base.tool.lib_hlyj_base.utils

import kotlinx.coroutines.CoroutineScope

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

//全局定时器
object GlobalTimer {
    private var timerJob: Job? = null
    private var isPaused = false

    private var lastTriggerTime: Long = 0L  // 记录上次触发时间
    private var currentInterval: Long = 0L  // 记录当前间隔
    fun start(intervalMillis: Long, action: () -> Unit) {
        stop()
        timerJob = CoroutineScope(Dispatchers.Default).launch {
            while (isActive) {
                if (!isPaused) {
                    val elapsed = System.currentTimeMillis() - lastTriggerTime
                    val remainingDelay = maxOf(0, intervalMillis - elapsed)  // 计算剩余等待时间
                    delay(remainingDelay)
                    withContext(Dispatchers.Main) {
                        action()
                    }
                    lastTriggerTime = System.currentTimeMillis()  // 更新触发时间
                } else {
                    delay(100) // 降低暂停时的CPU消耗
                }
            }
        }
    }

    fun pause() {
        isPaused = true
    }

    fun resume() {
        isPaused = false
    }

    fun stop() {
        timerJob?.cancel()
        timerJob = null
        isPaused = false
        lastTriggerTime = 0L
    }
    /**
     * 重置定时器（清零剩余时间，立即重新开始计时）
     */
    fun reset() {
        if (timerJob?.isActive == true) {
            lastTriggerTime = System.currentTimeMillis() - currentInterval  // 强制让剩余时间=0，使下一次 delay 立即执行
        }
    }
}